package src;

import java.util.ArrayList;
import java.util.List;

class Hit{

	
	private String ip;
	private long timeStamp;
	
	public Hit(String ip, long timeStamp){
		this.ip = ip;
		this.timeStamp = timeStamp;
	}
	
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public long getTimeStamp() {
		return timeStamp;
	}
	public void setTimeStamp(long timeStamp) {
		this.timeStamp = timeStamp;
	}
	
	@Override
	public boolean equals(Object hit){
		if(((Hit)hit).getIp().equals(this.getIp())){
			return true;
		}else{
			return false;
		}
	}
	
}

public class DOS {

	public static final long MAX_HITS = 10, TIME_WINDOW = (30*1000);//30 secs
	public static List<Hit> webHits = new ArrayList<Hit>();
	
	public static void main(String[] args) {

		while(true){//test code
			boolean isDos = isDos("10.10.10.10");
			System.out.println("isDos: "+isDos);
			if(isDos){
				break;
			}
		}
		
	}
	
	public static boolean isDos(String ip){
		
		long currentTime = System.currentTimeMillis();
		webHits.add(new Hit(ip, currentTime));//store the current hit
		
		int ipHitCnt = 0;
		for(Hit h: webHits){//iterate over the stored hits to find if the current hit is exceeding MAX_HITS for the given TIME_WINDOW
			if((currentTime - h.getTimeStamp()) > TIME_WINDOW){//if its a old hit the no need of storing it, remove
				webHits.remove(h);
				continue;
			}
			
			if(h.getIp().equals(ip)){//this hit falls under the TIME_WINDOW, check the timestamp
				ipHitCnt++;
				if(ipHitCnt >= MAX_HITS){//number of hits exceeded in the given TIME_WINDOW, considerring it a DOS Attack
					return true;
				}
			}
			
		}
		
		return false;//No DOS found, returning false
	}

}
